package com.lhkk.inventoryvehicle.rfid

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.cj.mvvmlib.util.ToastUtil
import com.gg.reader.api.dal.HandlerTagEpcLog
import com.gg.reader.api.protocol.gx.EnumG
import com.gg.reader.api.protocol.gx.LogBaseEpcInfo
import com.gg.reader.api.protocol.gx.MsgBaseInventoryEpc
import com.gg.reader.api.protocol.gx.MsgBaseStop
import com.gg.reader.api.utils.ThreadPoolUtils
import com.lhkk.inventoryvehicle.http.handler


object RfidManager {
    private val gClient = GlobalClient.getClient()
    private val tagInfoList = mutableMapOf<String, Int>()
    private const val ant1 = 1L //一个天线
    private const val ant2 = 3L //两个天线
    private const val TAG = "DeviceManager"
    val result = MutableLiveData<LogBaseEpcInfo>()
    fun connectDevice(callback: (Boolean) -> Unit) {
        val param = "/dev/ttyS6:115200"
        if (gClient.openAndroidSerial(param, 1000)) {
            ToastUtil.showShortToast("设备连接成功")
            subHandler()
            callback(true)
        } else {
            ToastUtil.showShortToast("设备连接失败")
        }
    }

    //订阅
    private fun subHandler() {
        gClient.onTagEpcLog = HandlerTagEpcLog { readerName, info ->
            if (null != info && 0 == info.result) {
                handler.post {
                    tagInfoList[info.epc] = info.rssi
                    ToastUtil.showShortToast("读取到标签：${info.epc}，RSSI：${info.rssi}")
                }
            }
        }
    }

    /**
     * 读取标签
     */
    fun readeTag() {
        val msg = MsgBaseInventoryEpc()
        msg.antennaEnable = ant2
        msg.inventoryMode = EnumG.InventoryMode_Inventory
        ThreadPoolUtils.run {
            gClient.sendSynMsg(msg)
            if (0x00 == msg.rtCode.toInt()) {
                Log.d(TAG, "开始读卡")
                handler.post {
                    ToastUtil.showShortToast("开始读卡")
                }
            } else {
                Log.d(TAG, msg.rtMsg)
                handler.post {
                    ToastUtil.showShortToast(msg.rtMsg)
                }
            }
        }
    }

    /**
     * 停止读取
     */
    fun stopRead() {
        val msgStop = MsgBaseStop()
        ThreadPoolUtils.run {
            gClient.sendSynMsg(msgStop)
            if (0x00 == msgStop.rtCode.toInt()) {
                Log.d(TAG, "停止读取成功")
                handler.post {
                    ToastUtil.showShortToast("停止读取成功")
                }
            } else {
                Log.d(TAG, "停止读取失败")
                handler.post {
                    ToastUtil.showShortToast("停止读取失败")
                }
            }
        }
    }
}